package be.phl.mycinema.adapters;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import be.phl.mycinema.R;
import be.phl.mycinema.classes.DownloadImageTask;
import be.phl.mycinema.classes.Film;
import be.phl.mycinema.classes.MemoryCache;

public class MyGridAdapter extends BaseAdapter {

	private ArrayList<Film> myObjects;
	private LayoutInflater inflater;
	private MemoryCache memoryCache;

	public MyGridAdapter(ArrayList<Film> myObjects, Context context) {
		this.myObjects = myObjects;
		this.inflater = LayoutInflater.from(context);

		if (memoryCache == null) {
			memoryCache = MemoryCache.createMemoryCache(context);
		}
	}

	public int getCount() {
		return myObjects.size();
	}

	public Object getItem(int position) {
		return myObjects.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		
		ViewHolder holder;
		convertView = inflater.inflate(R.layout.film_cell, null);

		holder = new ViewHolder();
		holder.Afbeelding = (ImageView) convertView.findViewById(R.id.grid_image);

		Bitmap t = memoryCache.getBitmapFromMemCache(myObjects.get(position).getFilm_ID());
		if (t == null) {
			holder.Afbeelding.setImageResource(R.drawable.empty_photo);
			new DownloadImageTask(myObjects.get(position).getAfbeelding(), myObjects.get(position).getFilm_ID(), holder.Afbeelding, memoryCache).execute("");
		} else {
			holder.Afbeelding.setImageBitmap(t);
		}
		
		return convertView;
	}

	static class ViewHolder {
		ImageView Afbeelding;
	}

}
